<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
      <el-form
        :inline="true"
        :model="filters"
        :size="size"
        ref="filters"
        style="width: 100%"
      >
        <el-row class="search-input">
          <el-form-item prop="channelCode" label="渠道编码：">
            <el-input
              v-model="filters.channelCode"
              clearable
              placeholder="渠道编码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="channelName" label="渠道名称：">
            <el-input
              v-model="filters.channelName"
              clearable
              placeholder="渠道名称"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-refresh"
              :label="$t('action.reset')"
              type="primary"
              @click="resetForm('filters')"
            />
          </el-form-item>
          <el-form-item>
            <kt-button label="启用/停用" type="primary" @click="editStatus" />
          </el-form-item>
        </el-row>
        <el-form-item class="t_r w100">
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button
                icon="fa fa-refresh"
                @click="findPage(null)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button
                icon="fa fa-filter"
                @click="displayFilterColumnsDialog"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button
                icon="fa fa-file-excel-o"
                @click="downloadExcel"
              ></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </el-form>
    </div>
    <!--表格内容栏-->
    <Jic-table
      :height="350"
      :data="pageResult"
      :columns="filterColumns"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @handleDetail="handleDetail"
      @selectionChange="selectionChange"
      :showBatchDelete="false"
      ref="JicTable"
      :loading="pageLoading"
    ></Jic-table>
    <!--新增编辑界面-->
    <el-dialog
      title="添加渠道"
      width="600px"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="80px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-form-item label="渠道类型" prop="channelType">
          <el-select v-model="dataForm.channelType" style="width: 400px">
            <el-option label="自建渠道" value="1">自营</el-option>
            <el-option label="第三方电商" value="2">第三方入驻商家</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道编码" prop="channelCode">
          <el-input
            v-model="dataForm.channelCode"
            auto-complete="off"
            :disabled="false"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item label="渠道名称" prop="channelName">
          <el-input
            v-model="dataForm.channelName"
            auto-complete="off"
            :disabled="false"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item label="渠道类型" prop="channelMode">
          <el-select v-model="dataForm.channelMode" style="width: 400px">
            <el-option label="BBC" value="1">BBC</el-option>
            <el-option label="O2O" value="2">O2O</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="线下线上" prop="isOnline">
          <el-select v-model="dataForm.isOnline" style="width: 400px">
            <el-option label="线上" value="1">线上</el-option>
            <el-option label="线下" value="0">线下</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{
          $t("action.cancel")
        }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
          >{{ $t("action.submit") }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import JicTable from "@/views/Core/JicTable";
import KtButton from "@/views/Core/KtButton";
import { format, formatDate } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { exportExcel } from "@/utils/excel";

export default {
  components: {
    JicTable,
    KtButton,
    TableColumnFilterDialog,
  },
  data() {
    return {
      content: "",
      editorOption: {
        modules: {
          imageDrop: true,
        },
        theme: "snow",
      },
      size: "small",
      filters: {},
      columns: [],
      filterColumns: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
      },
      pageResult: {},

      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      dataFormRules: {
        channelType: [
          {
            required: true,
            message: "请选择渠道类型",
            trigger: "blur",
          },
        ],
        channelCode: [
          {
            required: true,
            message: "请输入渠道编码",
            trigger: "blur",
          },
          {
            min: 2,
            max: 8,
            message: "长度在 2 到 8 个字符",
            trigger: "blur",
          },
          {
            pattern: /^[^\u4e00-\u9fa5]+$/,
            message: "虚拟库编码不能包含汉字",
            trigger: "blur",
          },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
            message: "虚拟库编码不能包含特殊字符",
            trigger: "blur",
          },
        ],
        channelName: [
          {
            required: true,
            message: "请输入渠道名称",
            trigger: "blur",
          },
        ],
        channelMode: [
          {
            required: true,
            message: "请选择渠道类型",
            trigger: "blur",
          },
        ],
        isOnline: [
          {
            required: true,
            message: "线上线下",
            trigger: "blur",
          },
        ],
      },
      // 新增编辑界面数据
      dataForm: {
        channelCode: "",
        channelName: "",
        channelMode: "",
        channelType: "",
        isOnline: "",
      },
      shopList: [],
      statusList: [],
      checked: [],
      pageLoading: false, //列表加载
    };
  },
  methods: {
    // 获取分页数据
    findPage: function (data) {
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this_.pageLoading = true;
      this.utils.request.queryChannelList(this_.filters, function (res) {
        this_.pageLoading = false;
        if (res.data == null) {
          res.data = [];
          res.totle = 0;
        }
        this_.$refs.JicTable.findPage({
          content: res.data.rows,
          total: res.data.total,
        });
        // this_.pageResult = res.data;
        // this_.totalSize = Number(res.totle);
      });
    },
    // 显示新增界面
    handleAdd: function () {
      this.editDialogVisible = true;
      this.operation = true;
      this.$refs['dataForm'].resetFields();
    },
    //选择框
    selectionChange: function (params) {
      this.checked = params.selections;
    },
    // 删除
    handleDelete: function (data) {
      let id = data.params[0].id;
        var params = {};
        params.id = id;
        var this_ = this;
        this.utils.request.deleteChannelInfo(params, function (res) {
          if (res.code == "0000") {
            this_.$message({
              message: "操作成功",
              type: "success",
            });
            this_.findPage(null);
          } else {
            this_.$message({
              message: "操作失败, " + res.msg,
              type: "error",
            });
          }
        });
    },
    // 编辑页面
    handleEdit: function (data) {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate();
      }
      if (data.row.id != null) {
        this.statusShow = false;
      }
      this.editDialogVisible = true;
      this.operation = true;
      this.dialogVisible = true;
      this.submitShow = "";
      this.dataForm = {
        id: data.row.id,
        channelCode: data.row.channelCode,
        channelName: data.row.channelName,
        channelMode: data.row.channelMode,
        channelType: data.row.channelType,
        isOnline: data.row.isOnline,
      };
    },
    // 详情页面
    handleDetail: function () {
      this.$router.push({
        path: "/MerchantEditPage",
        query: {
          cid: data.row.id,
        },
      });
    },
    // 编辑
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);
            params.status = 1;
            var this_ = this;
            this.utils.request.editChannelInfo(params, function (res) {
              if (res.code == "0000") {
                this_.$message({
                  message: "操作成功",
                  type: "success",
                });

                                this_.$refs["dataForm"].resetFields();

                                this_.editDialogVisible = false;

                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
            });
          });
        }
      });
    },
    //启用停用
    editStatus: function () {
      if (this.checked.length != 1) {
        this.$message({
          message: "请选择一条数据进行处理！",
          type: "error",
          center: true,
          offset: 250,
          duration: 1000,
        });
      } else {
        let params = {};
        params.id = this.checked[0].id;
        if (this.checked[0].status == "0") {
          params.status = "1";
        } else if (this.checked[0].status == "1") {
          params.status = "0";
        }
        var this_ = this;
        this.utils.request.editChannelInfo(params, function (res) {
          this_.$message({
            message: "操作成功",
            type: "success",
            center: true,
            offset: 250,
            duration: 1000,
          });
          this_.findPage(null);
        });
      }
    },
    // 时间格式化
    dateFormat: function (row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.filters = {};
        this.findPage(null);
      }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function () {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function (data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function () {
      this.columns = [
        {
          prop: "channelCode",
          label: "渠道编码",
          minWidth: 50,
        },
        {
          prop: "channelName",
          label: "渠道名称",
          minWidth: 120,
        },
        {
          prop: "channelType",
          label: "渠道类型	",
          minWidth: 120,
          formatter: this.type,
        },
        {
          prop: "channelMode",
          label: "渠道模式",
          minWidth: 120,
          formatter: this.model,
        },
        {
          prop: "isOnline",
          label: "线下线上",
          minWidth: 120,
          formatter: this.online,
        },
        {
          prop: "status",
          label: "是否可用",
          minWidth: 120,
          formatter: this.status,
        },
        {
          prop: "createTime",
          label: "创建时间",
          minWidth: 120,
        },
      ];
      var temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    online: function (row, column, cellValue, index) {
      if (cellValue == 1) {
        return "线上";
      } else if (cellValue == 0) {
        return "线下";
      }
    },
    model: function (row, column, cellValue, index) {
      if (cellValue == 1) {
        return "BBC";
      } else if (cellValue == 2) {
        return "O&O";
      } else if (cellValue == 3) {
        return "B2C";
      } else if (cellValue == 4) {
        return "京东";
      } else if (cellValue == 5) {
        return "天猫";
      } else if (cellValue == 6) {
        return "B2B";
      }
    },
    type: function(row, column, cellValue, index) {
      if (cellValue == 1) {
        return "自建渠道";
      } else if (cellValue == 2) {
        return "第三方电商";
      }
    },
    status: function(row, column, cellValue, index) {
      if (cellValue == 1) {
        return "启用";
      } else if (cellValue == 0) {
        return "停用";
      }
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportData(this.filters, "商家管理");
        })
        .catch(() => {});
    },
    //excle导出
    exportData: function (filters, fileName) {
      let this_ = this;
      if (filters == undefined || filters == null) {
        filters = {};
      }
      filters.start = this.pageRequest.pageNum;
      filters.limit = this.pageRequest.pageSize;
      this.utils.request.queryChannelList(this_.filters, function (res) {
        debugger;
        //将查询到的数据处理
        for (let i = 0; i < res.data.rows.length; i++) {
          res.data.rows[i].channelType = this_.type(
            null,
            null,
            res.data.rows[i].channelType,
            null
          );
          res.data.rows[i].channelModal = this_.model(
            null,
            null,
            res.data.rows[i].channelMode,
            null
          );
          res.data.rows[i].isOnline = this_.online(
            null,
            null,
            res.data.rows[i].isOnline,
            null
          );
          if (res.data.rows[i].status === "true") {
            res.data.rows[i].status = "启用";
          } else {
            res.data.rows[i].status = "禁用";
          }
        }
        fileName = fileName + "_" + formatDate(new Date(), "yyyyMMdd");
        exportExcel(res.data.rows, this_.filterColumns, fileName);
      });
    },
  },
  mounted() {
    this.initColumns();
    this.findPage();
  },
};
</script>

<style lang="scss" scoped>
.search-button {
  .el-form-item {
    &:last-of-type {
      margin-right: 0px !important;
    }
  }
}
</style>
